package com.zz.util;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 本地文件
 * @author vivijin
 *
 */
public class LocalFileUtil {

	/**
	 * 获取文件的byte[]数据
	 * 
	 * @param path
	 * @return
	 * @throws java.io.FileNotFoundException,java.io.IOException
	 */
	public static byte[] localBufferRead(String path) throws FileNotFoundException,IOException {
		File file = new File(path);
		if (!file.exists()) {
			return null;
		}
		FileInputStream inputFile = new FileInputStream(file);
		byte[] buffer = new byte[(int) file.length()];
		try {
			inputFile.read(buffer);
		} catch (IOException e) {
			throw e;
		} finally {
			if (inputFile != null) {
				try {
					inputFile.close();
				} catch (IOException e) {
					throw e;
				}
			}
		}
		return buffer;
	}

	public static void localBufferWrite(byte[] buffer, String targetPath,boolean isAddEndum,String encording) throws IOException {

		cMkdirs(targetPath.substring(0,targetPath.lastIndexOf("/")));
		FileOutputStream out = new FileOutputStream(targetPath);
		try {
			out.write(buffer);
			File file = new File(targetPath);
			file.setWritable(true, false);
		} catch (IOException e) {
			throw e;
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					throw e;
				}
			}
		}
	}
	public static void localBufferWrite(byte[] buffer, String targetPath) throws IOException {

		cMkdirs(targetPath.substring(0,targetPath.lastIndexOf("/")));
		FileOutputStream out = new FileOutputStream(targetPath);
		try {
			out.write(buffer);
			File file = new File(targetPath);
			file.setWritable(true, false);
		} catch (IOException e) {
			throw e;
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					throw e;
				}
			}
		}
	}
	/**
	 * 删除某个文件夹下的所有文件夹和文件
	 *
	 * @param delpath
	 *            String
	 * @throws java.io.FileNotFoundException
	 * @throws java.io.IOException
	 * @return boolean
	 */
	public static boolean localDeletefiles(String delpath)
			throws FileNotFoundException, IOException {
		boolean flag = false;
        //如果sPath不以文件分隔符结尾，自动添加文件分隔符
    	File dirFile = new File(delpath);
        if (!(dirFile.isFile()) && !delpath.endsWith(File.separator)) {
        	delpath = delpath + File.separator;
        }

        //如果dir对应的文件不存在，或者不是一个目录，则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
		try {
			File file = new File(delpath);
			if (!file.isDirectory()) {
				if(file.delete()){
					return true;
				}else{
					return false;
				}
			} else if (file.isDirectory()) {
				String[] filelist = file.list();
				for (int i = 0; i < filelist.length; i++) {
					File delfile = new File(delpath + "" + filelist[i]);
					if (!delfile.isDirectory()) {
						if(delfile.delete()){
							flag = true;
						}else{
							flag = false;
						}
						if (!flag) break;
					} else if (delfile.isDirectory()) {
						flag = localDeletefiles(delpath + "" + filelist[i]);
						if (!flag) break;
					}
				}
			}
		} catch (FileNotFoundException e) {
			//System.out.println("deletefile() Exception:" + e.getMessage());
		}
        if (!flag) return false;
        //删除当前目录
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
	}


	/**
	 *
	 * 读取某个文件夹下的所有文件夹和文件, 返回所有文件名
	 *
	 * @param filepath
	 *            String
	 * @throws java.io.FileNotFoundException
	 * @throws java.io.IOException
	 * @return Map<Integer, String> pathMap
	 *
	 */
	public static List localGetFilesName(String frompath, List files) {
		File file = new File(frompath);
		// 文件
		if (!file.isDirectory()) {
		} else if (file.isDirectory()) { // 如果是目录， 遍历所有子目录取出所有文件名
			String[] filelist = file.list();
			for (int i = 0; i < filelist.length; i++) {
				File readfile = new File(frompath + "/" + filelist[i]);
				if (!readfile.isDirectory()) {
					files.add(filelist[i]);
				} else if (readfile.isDirectory()) { // 子目录的目录
					localGetFilesName(frompath + "/" + filelist[i], files);
				}
			}
		}
		return files;
	}



	/**
	 *
	 * 读取某个文件夹下的所有文件夹和文件, 返回所有文件名
	 *
	 * @param filepath
	 *            String
	 * @throws java.io.FileNotFoundException
	 * @throws java.io.IOException
	 * @return Map<Integer, String> pathMap
	 *
	 */
	public static Map<Integer, String> localReadfile(String filepath,
			Map<Integer, String> pathMap) throws Exception {
		if (pathMap == null) {
			pathMap = new HashMap<Integer, String>();
		}
		File file = new File(filepath);
		// 文件
		if (!file.isDirectory()) {
			pathMap.put(pathMap.size(), file.getPath());
		} else if (file.isDirectory()) { // 如果是目录， 遍历所有子目录取出所有文件名
			String[] filelist = file.list();
			for (int i = 0; i < filelist.length; i++) {
				File readfile = new File(filepath + "/" + filelist[i]);
				if (!readfile.isDirectory()) {
					pathMap.put(pathMap.size(), readfile.getPath());
				} else if (readfile.isDirectory()) { // 子目录的目录
					localReadfile(filepath + "/" + filelist[i], pathMap);
				}
			}
		}
		return pathMap;
	}
    /**
     * 删除单个文件
     * @param   sPath    被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     * @throws java.io.IOException
     * @throws java.io.FileNotFoundException
     */
    public static boolean localDeleteFile(String url) throws FileNotFoundException, IOException {
    	return localDeletefiles(url);
    }
    /**
     * 删除单个文件
     * @param   sPath    被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     * @throws java.io.IOException
     * @throws java.io.FileNotFoundException
     */
    public static boolean localDeleteDirectory(String url) throws FileNotFoundException, IOException {
    	return localDeletefiles(url);
    }
    public static List<Map<String, Object>> localGetFilesList(String frompath,
			List<Map<String, Object>> files) {
		File file = new File(frompath);
		// 文件
		if (!file.isDirectory()) {
		} else if (file.isDirectory()) { // 如果是目录， 遍历所有子目录取出所有文件名
			String[] filelist = file.list();
			Map<String, Object> map = null;
			for (int i = 0; i < filelist.length; i++) {
				File readfile = new File(frompath + "/" + filelist[i]);
				if (!readfile.isDirectory()) {
					map = new HashMap<String, Object>();
					map.put("name", readfile.getName());
					map.put("path", readfile.getPath());
					map.put("size", localGetFileByte(readfile.getPath()));
					files.add(map);
				} else if (readfile.isDirectory()) { // 子目录的目录
					localGetFilesList(frompath + "/" + filelist[i], files);
				}
			}
		}
		return files;
	}

	public static long localGetFileByte(String filePath) {
		File f = new File(filePath);
		try {
			FileInputStream fis = new FileInputStream(f);
			try {
				//System.out.println(fis.available());
				return fis.available();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			return 0L;
		} catch (FileNotFoundException e2) {
			e2.printStackTrace();
		}
		return 0L;
	}
	/**
	 *
	 * @param path1
	 * @param name1
	 * @param path2
	 * @param name2
	 * @return
	 */
	public static boolean copy(String path1, String name1, String path2,
			String name2) {
		return copy(path1 + name1, path2, name2);
	}

	public static boolean copy(String url, String path2, String name2) {
		File file1 = new File(url);
		if (!file1.exists()) {
			return false;
		}
//		File file2 = new File(path2);
//		if (!file2.exists()) {
//			file2.mkdirs();
//			file2.setWritable(true, false);
//		}
		mkdirs(path2);
		return copy(url, path2 + name2);
	}

	/**
	 *拷贝文件
	 *
	 * @param url 源路径
	 * @param url2 目标路径
	 * @return
	 */
	public static boolean copy(String url, String url2) {
		FileInputStream in1 = null;
		FileOutputStream out1 = null;
		try {
			File file_in = new File(url);
			if (!file_in.exists()) {
				return false;
			}
			File file_out = new File(url2);
			in1 = new FileInputStream(file_in);
			out1 = new FileOutputStream(file_out);
			byte[] bytes = new byte[1024];
			int c;
			while ((c = in1.read(bytes)) != -1)
				out1.write(bytes, 0, c);
			return true; // if success then return true
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				if (in1 != null) {
					in1.close();
				}
				if (out1 != null) {
					out1.flush();
					out1.close();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}



	/**
	 *
	 * copy某个文件夹下的所有文件夹和文件
	 *
	 * @param filepath
	 *            String
	 * @throws java.io.FileNotFoundException
	 * @throws java.io.IOException
	 * 
	 */
	public static void copyfiles(String frompath, String topath) {
		File file = new File(frompath);
		// 文件
		if (!file.isDirectory()) {
		} else if (file.isDirectory()) { // 如果是目录， 遍历所有子目录取出所有文件名
			String[] filelist = file.list();
			for (int i = 0; i < filelist.length; i++) {
				File readfile = new File(frompath + "/" + filelist[i]);
				if (!readfile.isDirectory()) {
					copy(frompath + "/" + filelist[i], topath + "/",
							filelist[i]);
					// pathMap.put(pathMap.size(), readfile.getPath());
				} else if (readfile.isDirectory()) { // 子目录的目录
					copyfiles(frompath + "/" + filelist[i], topath + "/"
							+ filelist[i]);
				}
			}
		}
	}
	public  static void mkdirs (String path){

		if(!path.endsWith("/")){
			path +="/";
		}
		boolean exist = true;
		List<File> paths = new ArrayList<File>();
		File file = null;
		while(exist){
			file = new File(path);
			if(file.exists()){
				break;
			}
			paths.add(file);
			path = path.replaceAll("[a-zA-Z0-9\\-\\:\\：]+\\/$", "");
		}
        for(int i = paths.size()-1;i>=0;i--){
        	((File)paths.get(i)).mkdir();
        	((File)paths.get(i)).setWritable(true, false);
        }
	}
	
	public  static void cMkdirs (String path){

		if(!path.endsWith("/")){
			path +="/";
		}
		File file = new File(path);
			if(!file.exists()){
				file.mkdirs();
			}
	}
	
	public static void main(String[] args) throws FileNotFoundException, IOException {
		String ss = "/appfs/sdltApp/uploadfile/pdf/2015/02/07/：/";
		ss = ss.replaceAll("[a-zA-Z0-9\\-\\：]+\\/$", "");
		//System.out.println(ss);
		/*String filePath = ConstUtil.getFileUploadPath(ConstUtil.UPLOADFILE_PDF)+"2015/01/30/SC20150130115908/1422590348959.pdf";
		//System.out.println(filePath);
		byte[] bb = localBufferRead(filePath);
		//System.out.println( new String(Base64.encodeBase64(bb)));*/
	//	localBufferWrite(new BASE64Decoder().decodeBuffer((new BASE64Encoder().encode(bb))), filePath+1, true, "");
//		ss="a/njdxApp/certs/2012/";
//		File file = new File(ss);
//		//System.out.println(file.exists());
//		if(!file.exists())
//		{
//			file.mkdirs();
//		}
		 String dir = System.getProperty("user.dir");
		    dir = dir + File.separator + "arptmp";
		    //System.out.println(dir);
		    //System.out.println(File.separator);
    }

}


